package main

import (
	"hostip2dns/config"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"log"
	
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
	dnspod "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v20210323"
)

func main() {
	logger := log.New(os.Stdout, "", log.LstdFlags)
	ip, err := getCurrentIp()
	if err != nil {
		panic(err)
	}

    // 获取可执行文件的路径
    exePath, err := os.Executable()
    if err != nil {
        logger.Println("Error:", err)
        return
    }

    // 获取可执行文件的目录
    exeDir := filepath.Dir(exePath)
	filePath, err := filepath.Abs(exeDir+"/config/ip")
	if err != nil {
		panic(err)
	}
	oldIp, err := ioutil.ReadFile(filePath)
	if err != nil{
		panic(err)
	}
	if string(oldIp) == ip {
		logger.Println("ip has not changed")
		os.Exit(0)
	}else{
		logger.Println("ip changed: %s => %s", oldIp, ip)
	}
	tcCfg := config.Config(exeDir+"/config/config.toml").Tc
	credential := common.NewCredential(tcCfg.AccessKeyId, tcCfg.AccessKeySecret)
	client, _ := dnspod.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())

	request := dnspod.NewModifyRecordRequest()
	request.Domain = &tcCfg.Domain
	request.RecordId = tcCfg.RecordId
	request.Value = &ip
	request.RecordLine = &tcCfg.RecordLine
	request.RecordType = &tcCfg.RecordType
	request.SubDomain = &tcCfg.SubDomain
	response, err := client.ModifyRecord(request)

	if _, ok := err.(*errors.TencentCloudSDKError); ok {
		logger.Println("An API error has returned: %s", err)
		return
	}
	if err != nil {
		panic(err)
	}
	logger.Println("%s", response.ToJsonString())

	f, err := os.OpenFile(filePath, os.O_RDWR|os.O_TRUNC|os.O_CREATE, os.ModePerm)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	_, err = f.WriteString(ip)
	if err != nil {
		panic(err)
	}
}

func getCurrentIp() (_result string, _err error) {
	url := "http://ip.boolh.com"
	resp, _err := http.Get(url)
	if _err != nil {
		panic(_err)
	}
	defer resp.Body.Close()

	body, _err := io.ReadAll(resp.Body)
	ip := net.ParseIP(string(body))
	if ip == nil {
		panic("err ip")
	}
	return ip.String(), _err
}
